<template>
    <div class="inner-warp">
        <MainTitleVue title="学者门户" />
        <div class="sub-warp">
            <!-- 类型栏 -->
            <div class="type-bar">
                <n-button
                    round
                    size="small"
                    color="#825CF7"
                    ghost
                    class="share-button"
                    @click="copyLink"
                    :data-clipboard-text="shareLink"
                >
                    <template #icon>
                        <n-icon>
                            <share-icon />
                        </n-icon>
                    </template>
                    分享
                </n-button>
                <n-button
                    round
                    size="small"
                    color="#FFBB1C"
                    :ghost="!author_data.is_collected"
                    class="collect-button"
                    @click="starAuthor"
                >
                    <template #icon>
                        <n-icon>
                            <focus-icon />
                        </n-icon>
                    </template>
                    {{ author_data.is_collected ? "已关注" : "关注" }}
                </n-button>
                <n-button
                    round
                    size="small"
                    color="#48D479"
                    :ghost="!author_data.is_claimed"
                    class="claim-button"
                    @click="claim"
                >
                    <template #icon>
                        <n-icon>
                            <claim-icon />
                        </n-icon>
                    </template>
                    {{ author_data.is_claimed ? "已认领" : "认领" }}
                </n-button>
            </div>
            <n-divider style="width: 0;" />
            <!-- 姓名与头像 -->
            <n-grid x-gap="2" :cols="10">
                <n-gi span="2">
                    <n-avatar
                        round
                        :size="120"
                        :src="author_data.url_picture"
                        :fallback-src="default_avatar"
                    />
                </n-gi>
                <n-gi span="8" style="margin: auto 0;">
                    <span class="author-name">{{ author_data.name }}</span>
                </n-gi>
            </n-grid>
            <n-divider />
            <!-- 信息简介 -->
            <div class="detail-bar">
                <span style="font-weight: bold;">机构：</span>
                <n-text
                    underline
                    @click="author_data.org.id !== '-1' ? router.push({ name: 'Org', params: { id: author_data.org.id } }) : ''"
                    style="cursor: pointer;"
                >{{ author_data.org.id !== '-1' ? author_data.org.name : '未收录' }}</n-text>
            </div>
            <n-divider />
            <div class="detail-bar">
                <span style="font-weight: bold;white-space: nowrap;">研究方向：</span>
                <div v-for="(item, index) in author_data.interests" :key="'author' + index">
                    <n-text v-if="index !== 0" style="white-space: nowrap;">&nbsp;,&nbsp;</n-text>
                    <n-text style="white-space: nowrap;">{{ (item as any).name }}</n-text>
                </div>
            </div>
            <n-divider />
            <div class="detail-bar">
                <span style="font-weight: bold;">职位：</span>
                <n-text>{{ author_data.affiliation }}</n-text>
            </div>
            <n-divider />
            <div class="detail-bar">
                <span style="font-weight: bold;">被引次数：</span>
                <n-text>{{ author_data.cited_time }}</n-text>
            </div>
            <n-divider />
            <div class="detail-bar">
                <span style="font-weight: bold;">最新成果：</span>
                <n-text
                    underline
                    @click="router.push({ name: 'PaperIntro', params: { id: author_data.latest_achievements.id } })"
                    style="cursor: pointer;"
                >{{ author_data.latest_achievements.name }}</n-text>
            </div>
            <n-divider />
            <div class="detail-bar" v-if="!author_data.is_claimed">
                <span style="font-weight: bold;">个人简介：</span>
                <n-text v-if="!is_edit" style="cursor: pointer;">{{ author_data.intro }}</n-text>
                <n-button
                    v-if="!is_edit && author_data.claimed_by_user"
                    class="edit-intro"
                    @click="editIntro"
                    size="tiny"
                >修改</n-button>
                <n-input
                    v-if="is_edit"
                    type="text"
                    v-model:value="author_data.intro"
                    placeholder="个人简介，可输入邮箱等信息"
                    maxlength="48"
                    show-count
                    clearable
                    size="small"
                    style="max-width: 70%;"
                >{{ author_data.intro }}</n-input>
                <n-button v-if="is_edit" class="save-intro" @click="saveIntro" color="#333333">保存</n-button>
                <n-button v-if="is_edit" class="cancel-intro" @click="cancelIntro">取消</n-button>
            </div>
            <n-divider v-if="!author_data.is_claimed" />
            <n-card class="echart-card">
                <AuthorRelation :pid="id" />
            </n-card>
            <n-card class="echart-card">
                <AuthorPaper />
            </n-card>
            <div class="result-count">
                <div></div>
                <n-text italic>{{ countFormat(result_count) }}</n-text>
                <n-text>&nbsp;学术成果</n-text>
            </div>
            <!-- 排序方式切换 -->
            <div class="rank-type">
                <n-switch @update:value="changeRankType" v-model:value="rank_type">
                    <template #checked>最新发表</template>
                    <template #unchecked>最多被引</template>
                </n-switch>
            </div>
            <PaperList
                :page="page"
                :page_size="page_size"
                :papers="papers"
                :result_count="result_count"
                @update-page="updagePage"
                @update-page-size="updagePageSize"
            />
        </div>
    </div>
</template>

<script setup lang='ts'>
import MainTitleVue from "@/components/common/MainTitle.vue";
import { getCurrentInstance, ref, onMounted } from "vue";
import { useMessage } from 'naive-ui'
import { useRouter } from 'vue-router';
import Clipboard from 'clipboard'
import PaperList from '@/components/search/PaperList.vue'
import AuthorPaper from '@/views/entity/components/AuthorPaper.vue'
import AuthorRelation from '@/views/entity/components/AuthorRelation.vue'
import { AccessibilityOutline as ClaimIcon, ShareSocialOutline as ShareIcon } from '@vicons/ionicons5'
import { AutoAwesomeOutlined as FocusIcon } from '@vicons/material'

// 引入路由
const router = useRouter()

//用于Message弹框
const message = useMessage()

// api访问代理
const { proxy } = getCurrentInstance() as any

//获取学者id
const id = router.currentRoute.value.params.id

const shareLink = "http://121.36.93.104/author/" + router.currentRoute.value.params.id

// 默认头像
const default_avatar = "https://xs2.dailyheadlines.cc/citations/images/avatar_scholar_128.png"

// 搜索结果数
const result_count = ref(15)

// 初始页数和每页展示数
const page = ref(1)
const page_size = ref(10)

// 排序方式
const rank_type = ref(false)

// 是否在设置个人简介
const is_edit = ref(false)
// 临时保存个人简介
const temp_intro = ref("")

//检索结果
let papers = ref([{
    id: 1,
    title: "Hop Language: A Language Learning App Empowered by Deep Learning",
    venue: {
        id: 0,
        name: 'IEEE'
    },
    year: 2020,
    abstract: 'With the amazing advancement of mobile technology, people can easily learn a new language from their mobile devices. Exploring popular language learning apps, we discovered that speech and handwriting recognition functionalities are lacking in these.',
    quote_time: 10,
    download_time: 5,
    author: [
        {
            id: 1,
            name: "Maisa Hamdan",
        },
        {
            id: 2,
            name: "Margaret Blackmon",
        }
    ],
}])

// 学者信息
let author_data = ref({
    name: "",
    //   研究方向
    interests: [

    ],
    //   机构
    org: {
        id: '',
        name: "",
    },
    //   被引用数
    cited_time: 0,
    //   已收藏
    is_collected: false,
    //   已认领
    is_claimed: false,
    //   是否被当前用户认领
    claimed_by_user: false,
    //   最新成果
    latest_achievements: {
        name: "",
        id: "",
    },
    //   头像地址
    url_picture: default_avatar,
    //   简介
    intro: "该学者还未设置个人简介",
    // 职位
    affiliation: ''
});

onMounted(() => {
    init()
})

const init = (() => {
    getAuthorDetail()
    getAuthorPapers()
})

// 获取作者信息
const getAuthorDetail = (() => {
    proxy.$api.entity.getAuthorDetail({ id: id }).then((result: any) => {
        if (result.success) {
            author_data.value = result.author_data
            author_data.value.url_picture = "https://images.xueshu.lanfanshu.cn/citations?view_op=medium_photo&user=" + id
        } else {
            message.warning(result.msg)
        }
    }).catch(() => {
        message.error('未知错误')
    });
})

// 修改个人简介
const editIntro = (() => {
    temp_intro.value = author_data.value.intro;
    is_edit.value = true;
})

// 保存个人简介的修改
const saveIntro = (() => {
    is_edit.value = false;
    proxy.$api.entity.editIntro({ id: id, intro: author_data.value.intro }).then((result: any) => {
        if (result.success) {
            message.success("保存成功")
        } else {
            message.warning(result.msg)
        }
    }).catch(() => {
        message.error('未知错误')
    });
})

// 取消个人简介的修改
const cancelIntro = (() => {
    is_edit.value = false;
    author_data.value.intro = temp_intro.value;
})

// 获取作者论文
const getAuthorPapers = (() => {
    var params = {
        id: id,
        rank_type: rank_type.value ? 1 : 2,
        page: page.value,
        page_size: page_size.value
    }
    proxy.$api.entity.getAuthorPapers(params).then((result: any) => {
        if (result.success) {
            result_count.value = result.result_count
            papers.value = result.papers
        } else {
            message.warning(result.msg)
        }
    }).catch(() => {
        message.error('未知错误')
    });
})

// 更改排序方式
const changeRankType = ((value: boolean) => {
    rank_type.value = value
    getAuthorPapers()
})

// 更新页码
const updagePage = ((value: number) => {
    page.value = value
    getAuthorPapers()
})

// 更新页条目数
const updagePageSize = ((value: number) => {
    page.value = 1
    page_size.value = value
    getAuthorPapers()
})

// 收藏/取消收藏
const starAuthor = (() => {
    proxy.$api.user.starAuthor({ id: id }).then((result: any) => {
        if (result.success) {
            if (author_data.value.is_collected) {
                message.success("取消关注成功")
            } else {
                message.success("关注成功")
            }
            author_data.value.is_collected = !author_data.value.is_collected
        } else {
            message.warning(result.msg)
        }
    }).catch(() => {
        message.error('未知错误')
    });
})

// 认领学者主页
const claim = (() => {
    if (author_data.value.is_claimed) {
        message.warning("该门户已被认领")
        return
    }

    router.push({ name: "Claim", query: { id: id } })
})

const countFormat = ((_num: number) => {
    var num = (_num || 0).toString()
    var result = '';
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) { result = num + result; }
    return result;
})

// 复制链接
const copyLink = (() => {
    let clipboard = new Clipboard('.share-button')
    clipboard.on('success', () => {
        message.success("已复制分享地址")
        clipboard.destroy()
    })
    clipboard.on('error', () => {
        message.error("复制地址失败，请重试")
        clipboard.destroy()
    })
})
</script>

<style scoped>
.inner-warp {
    margin: 50px auto;
    height: 100%;
    width: 1100px;
}

.sub-warp {
    margin: 3% 13%;
}

.type-bar {
    font-weight: bold;
}

.type-bar :deep(.n-button) {
    float: right;
    margin-right: 10px;
}

.author-name {
    font-size: 32px;
}

.claim-button {
    padding-right: 10px;
    padding-left: 10px;
}

.collect-button {
    padding-right: 10px;
    padding-left: 10px;
}

.share-button {
    padding-right: 10px;
    padding-left: 10px;
}
.detail-bar {
    display: flex;
}

.detail-bar :deep(.n-text) {
    color: #8d8a8a;
}

.rank-type {
    float: right;
}

.rank-type :deep(.n-switch) {
    margin-left: 20px;
    --rail-color: #333333 !important;
    --rail-color-active: #40acbb !important;
}

.result-count {
    margin-top: 10px;
    display: flex;
}

.result-count :deep(div) {
    background: #ebc34a;
    height: 20px;
    width: 4px;
    margin-right: 5px;
}

.echart-card {
    margin-top: 10px;
    height: 500px;
    width: 98%;
    font-size: 60px;
    font-weight: bold;
    box-shadow: 0 8px 8px hsl(0deg 0% 78% / 50%);
}

.edit-intro {
    margin-left: 2%;
}
.save-intro {
    outline-color: #333333;
    margin-top: 2px;
    margin-left: 1.4%;
}
.cancel-intro {
    margin-top: 2px;
    margin-left: 1%;
}
</style>